package com.hd.common.taobao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hd.assistant.biz.manager.ordermining.OrderMiningManager;
import com.hd.common.taobao.notify.CommonConnectionLifeCycleListener;
import com.hd.common.taobao.notify.CommonTopCometMessageListener;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.AppCustomer;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Sku;
import com.taobao.api.domain.User;
import com.taobao.api.internal.stream.Configuration;
import com.taobao.api.internal.stream.TopCometStream;
import com.taobao.api.internal.stream.TopCometStreamFactory;
import com.taobao.api.internal.stream.TopCometStreamRequest;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.IncrementCustomerPermitRequest;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemsInventoryGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.TopatsResultGetRequest;
import com.taobao.api.request.TopatsTradesSoldGetRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.request.TradesSoldIncrementGetRequest;
import com.taobao.api.request.UserSellerGetRequest;
import com.taobao.api.request.VasSubscribeGetRequest;
import com.taobao.api.response.IncrementCustomerPermitResponse;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemsInventoryGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.TopatsResultGetResponse;
import com.taobao.api.response.TopatsTradesSoldGetResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
import com.taobao.api.response.TradesSoldIncrementGetResponse;
import com.taobao.api.response.UserSellerGetResponse;
import com.taobao.api.response.VasSubscribeGetResponse;


public class DefaultTaobaoISVAppManager {

	private String authUrl;
	private String topUrl;
	private String notifyUrl;
	private String tokenUrl;
	private String orderAppKey;
	private String orderAppSecret;
	private String orderAppRedirectUrl;
	
	private String shareAppKey;
	private String shareAppSecret;
	private String shareAppRedirectUrl;
	
	@Autowired
	OrderMiningManager orderMiningManager;
	public void init(){
		if(orderAppKey == null)
			return;
		Set<TopCometStreamRequest> cometReqs = new HashSet<TopCometStreamRequest>();
		TopCometStreamRequest cometReq1 = new TopCometStreamRequest(orderAppKey,orderAppSecret,null,"1");
		TopCometStreamRequest cometReq2 = new TopCometStreamRequest(orderAppKey,orderAppSecret,null,"2");
		/*可选为每个连接指定连接监听器和消息监听器，如果为每个连接指定了相对应的监听器，则对此连接会使用指定的监听器，否则会使用为TopCometStream 指定的全局监听器,建议为每个连接指定自己的监听器，方便将来查找问题，在指定监听器时最好能做到很容器的区分出来不同连接的监听器*/

	/*	cometReq1.setConnectListener(ConnectionLifeCycleListener接口的实现类);
		cometReq1.setMsgListener(TopCometMessageListener接口的实现类);*/
		
	/*	cometReq2.setConnectListener(ConnectionLifeCycleListener接口的实现类);
		cometReq2.setMsgListener(TopCometMessageListener接口的实现类);*/
		cometReqs.add(cometReq1);
		cometReqs.add(cometReq2);
		
		Configuration conf = new Configuration(cometReqs);
		if(topUrl != null)
			conf.setRestApiUrl(topUrl);
		if(notifyUrl != null)
			conf.setConnectUrl(notifyUrl);
		TopCometStream stream = new TopCometStreamFactory(conf).getInstance();

		/*如果为每个连接指定了自己的监听器，则这里可以不指定，如果没有为每个连接指定自己的监听器，则在这里需要设定全局监听器，每个连接都将使用这个全局监听器*/
		stream.setConnectionListener(new CommonConnectionLifeCycleListener());
		stream.setMessageListener(new CommonTopCometMessageListener(this.orderMiningManager));
		stream.start();
	}
	
	public String getShareAppKey() {
		return shareAppKey;
	}

	public void setShareAppKey(String shareAppKey) {
		this.shareAppKey = shareAppKey;
	}

	public String getShareAppSecret() {
		return shareAppSecret;
	}

	public void setShareAppSecret(String shareAppSecret) {
		this.shareAppSecret = shareAppSecret;
	}

	public String getNotifyUrl() {
		return notifyUrl;
	}

	public void setNotifyUrl(String notifyUrl) {
		this.notifyUrl = notifyUrl;
	}

	public String getShareAppRedirectUrl() {
		return shareAppRedirectUrl;
	}

	public void setShareAppRedirectUrl(String shareAppRedirectUrl) {
		this.shareAppRedirectUrl = shareAppRedirectUrl;
	}

	public String getOrderAppKey() {
		return orderAppKey;
	}
	public void setOrderAppKey(String orderAppKey) {
		this.orderAppKey = orderAppKey;
	}
	public String getOrderAppSecret() {
		return orderAppSecret;
	}
	public void setOrderAppSecret(String orderAppSecret) {
		this.orderAppSecret = orderAppSecret;
	}
	public String getOrderAppRedirectUrl() {
		return orderAppRedirectUrl;
	}
	public void setOrderAppRedirectUrl(String orderAppRedirectUrl) {
		this.orderAppRedirectUrl = orderAppRedirectUrl;
	}
	public String getAuthUrl() {
		return authUrl;
	}
	public void setAuthUrl(String authUrl) {
		this.authUrl = authUrl;
	}
	public String getTopUrl() {
		return topUrl;
	}
	public void setTopUrl(String topUrl) {
		this.topUrl = topUrl;
	}
	
	public String getTokenUrl() {
		return tokenUrl;
	}
	public void setTokenUrl(String tokenUrl) {
		this.tokenUrl = tokenUrl;
	}
	public String getRedirectOrderAuth(){
		return this.authUrl+"?state=1212&view=web&client_id="+this.orderAppKey+"&response_type=code&scope=item&redirect_uri="+this.orderAppRedirectUrl;
	}
	public String getRedirectShareAuth(){
		return this.authUrl+"?state=1212&view=web&client_id="+this.shareAppKey+"&response_type=code&scope=item&redirect_uri="+this.shareAppRedirectUrl;
	}
	public JSONObject getOrderAuthInfoByCode(String code) throws IOException{
			return this.getAuthInfoByCode(code, this.orderAppKey, this.orderAppSecret, this.orderAppRedirectUrl);
	}
	public JSONObject getShareAuthInfoByCode(String code) throws IOException{
		return this.getAuthInfoByCode(code, this.shareAppKey, this.shareAppSecret, this.shareAppRedirectUrl);
}
	public JSONObject getAuthInfoByCode(String code,String appKey,String appSecret,String redirectUrl) throws IOException{
		 	Map<String, String> params = new HashMap<String, String>();
       
			params.put("response_type", "code");
			params.put("client_id", appKey);
			params.put("redirect_uri",
					redirectUrl);
			params.put("state", "1212");
			params.put("scope", "item");
			params.put("view", "web");
			params.put("code", code);
			params.put("client_secret",
					appSecret);
			params.put("grant_type", "authorization_code");
			String response = WebUtils.doPost(this.getTokenUrl(),
					params, 0, 0);
			JSONObject object = JSONObject.parseObject(response);
			return object;
	}
	public AppCustomer permitNotify(String appkey,String secret,String sessionKey) throws ApiException{
		TaobaoClient client3=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		
		IncrementCustomerPermitRequest req=new IncrementCustomerPermitRequest();
		req.setType("get,syn,notify");
		req.setTopics("trade;refund;topats;item");
		req.setStatus("all;all;all;ItemAdd,ItemUpdate");
		IncrementCustomerPermitResponse response = client3.execute(req , sessionKey);
		return  response.getAppCustomer();
	}
	
	public List<Item> getCurrentSellerAllOnSaleItems(String appkey,String secret,String sessionKey,Date startModify,Date endModify) throws ApiException{
		if(secret==null || sessionKey == null)
			return null;
		long start = System.currentTimeMillis();
		long pageSize = 200l;
		List<Item> rtn = new ArrayList<Item>();
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		ItemsOnsaleGetRequest req=new ItemsOnsaleGetRequest();
		req.setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		req.setPageSize(pageSize);
		if(startModify != null)
			req.setStartModified(startModify);
	    if(endModify != null)
	    	req.setEndModified(endModify);
		ItemsOnsaleGetResponse response = client.execute(req , sessionKey);
		if(response.getTotalResults() == 0)
			return rtn;
		if(response.getTotalResults() > pageSize){
			long page = response.getTotalResults()/pageSize;
			if(response.getTotalResults() % pageSize != 0){
				page = page + 1;
			}
			for(long i=2;i<=page;i++){
				req.setPageNo(i);
				response = client.execute(req , sessionKey);
				rtn.addAll(response.getItems());
			}
		}else{
			rtn.addAll(response.getItems());
		}
		long end = System.currentTimeMillis();
		System.out.println("getCurrentSellerAllOnSaleItems:"+(start-end));
		return rtn;
	}
	
	public List<Item> getCurrentSellerInventoryItems(String appkey,String secret,String sessionKey,Date startModify,Date endModify) throws ApiException{
		if(secret==null || sessionKey == null)
			return null;
		long start = System.currentTimeMillis();
		long pageSize = 200l;
		List<Item> rtn = new ArrayList<Item>();
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		ItemsInventoryGetRequest  req=new ItemsInventoryGetRequest ();
		req.setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		req.setPageSize(pageSize);
		if(startModify != null)
			req.setStartModified(startModify);
	    if(endModify != null)
	    	req.setEndModified(endModify);
	    ItemsInventoryGetResponse  response = client.execute(req , sessionKey);
		if(response.getTotalResults() == 0)
			return rtn;
		if(response.getTotalResults() > pageSize){
			long page = response.getTotalResults()/pageSize;
			if(response.getTotalResults() % pageSize != 0){
				page = page + 1;
			}
			for(long i=2;i<=page;i++){
				req.setPageNo(i);
				response = client.execute(req , sessionKey);
				rtn.addAll(response.getItems());
			}
		}else{
			rtn.addAll(response.getItems());
		}
		long end = System.currentTimeMillis();
		System.out.println("getCurrentSellerInventoryItems:"+(start-end));
		return rtn;
	}
	public ItemsOnsaleGetResponse getOnSaleItemsByRequest(ItemsOnsaleGetRequest req,String appkey,String secret,String sessionKey) throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		req.setFields("approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		ItemsOnsaleGetResponse response = client.execute(req , sessionKey);
		return response;
	}
	public Item getItemByItemId(ItemGetRequest req,String appkey,String secret,String sessionKey) throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		req.setFields("num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id");
		ItemGetResponse response = client.execute(req , sessionKey);
		if(response == null)
			return null;
		return response.getItem();
	}
	public List<Sku> getSkuInfosByItemId(String appkey,String secret,String sessionKey,String itemId) throws ApiException{
		
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		ItemGetRequest req=new ItemGetRequest();
		req.setFields("sku,property_alias");
		req.setNumIid(Long.parseLong(itemId));
		ItemGetResponse response = client.execute(req , sessionKey);
		Item item = response.getItem();
		List<Sku> skus = item.getSkus();
		String alias = item.getPropertyAlias();
		Map<String, String> aliasMap = new HashMap<String, String>();
		if(alias != null){
			String aps [] = StringUtil.split(alias, ";");
			if(aps != null && alias.length() >0){
				for(String p : aps){
					String ss[] = StringUtil.split(p, ":");
					if(ss!=null && ss.length==3){
						aliasMap.put(ss[0]+":"+ss[1], ss[2]);
					}
				}

			}
		}
		for(Sku sku : skus){
			sku.setPropertiesAlias(generateSkuDisplay(sku.getPropertiesName(),aliasMap));
		}
		return skus;
	}
	private String generateSkuDisplay(String name,Map<String, String> display) {
		if (name == null)
			return name;
		try {
			StringBuffer sb = new StringBuffer();
			String[] props = name.split(";");
			for (String p : props) {
				String ss[] = p.split(":");
				if (ss != null && ss.length == 4) {
					String key = ss[0]+":"+ss[1];
					if(display.containsKey(key)){
						String d = display.get(key);
						sb.append(ss[2]).append("[").append(d).append("]-");
					}else{
						sb.append(ss[2]).append("[").append(ss[3]).append("]-");
					}
					
				}
			}
			return sb.substring(0, sb.length() - 1);
		} catch (Exception e) {
			return name;
		}
	}
	
	public User getCurrentUserInfo(String appkey,String secret,String sessionKey) throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		UserSellerGetRequest req=new UserSellerGetRequest();
		req.setFields("user_id,nick,sex,seller_credit,type,has_more_pic,item_img_num,item_img_size,prop_img_num,prop_img_size,auto_repost,promoted_type,status,alipay_bind,consumer_protection,avatar,liangpin,sign_food_seller_promise,has_shop,is_lightning_consignment,has_sub_stock,is_golden_seller,vip_info,magazine_subscribe,vertical_market,online_gaming");
		UserSellerGetResponse response = client.execute(req , sessionKey);
		return response.getUser();
	}
	public TradesSoldGetResponse getTradesByCreateTime(String appkey,String secret,String sessionKey,TradesSoldGetRequest reqs) throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.getTopUrl(), appkey, secret);
		reqs.setFields("tid,num,created,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
		TradesSoldGetResponse responses = client.execute(reqs , sessionKey);
		return responses;
	}
	
	public TradesSoldIncrementGetResponse getIncrementTrades(String appkey,String secret,String sessionKey,TradesSoldIncrementGetRequest  req)throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		req.setFields("tid,num,created,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
		TradesSoldIncrementGetResponse  response = client.execute(req , sessionKey);
		return response;
	}
	public TopatsTradesSoldGetResponse getTrades(String appkey,String secret,String sessionKey,TopatsTradesSoldGetRequest  req)throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(this.topUrl, appkey, secret);
		req.setFields("tid,num,created,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
		TopatsTradesSoldGetResponse  response = client.execute(req , sessionKey);
		return response;
	}

	public TopatsTradesSoldGetResponse topatsGetAllTrades(String appkey,String secret,String sessionKey,TopatsTradesSoldGetRequest req,String start,String end)throws ApiException{
		req.setFields("tid,num,created,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
		TaobaoClient client=new DefaultTaobaoClient(getTopUrl(), appkey, secret);
		req.setStartTime(start);
		req.setEndTime(end);
		TopatsTradesSoldGetResponse response = client.execute(req , sessionKey);
		return response;
	}
	public TradeFullinfoGetResponse getTradeByTid(String appkey,String secret,String sessionKey,TradeFullinfoGetRequest req)throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(getTopUrl(), appkey, secret);
		req.setFields("tid,num,created,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
		TradeFullinfoGetResponse response = client.execute(req , sessionKey);
		return response;
	}
	public TopatsResultGetResponse  getTopatsByTaskid(String appkey,String secret,TopatsResultGetRequest  req)throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(getTopUrl(), appkey, secret);
		TopatsResultGetResponse response = client.execute(req);
		return response;
	}
	
	public static void main(String[] args) {
		TopatsResultGetRequest req = new TopatsResultGetRequest();
		req.setTaskId(178978151l);
		TaobaoClient client=new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "21587911", "aee342fa13f0ace36678ba0d506e3633");
		try {
			TopatsResultGetResponse response = client.execute(req);
			System.out.println(response.getBody());
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public VasSubscribeGetResponse getVasSubscribeInfo(String appkey,String secret,String nick,String articleCode )throws ApiException{
		TaobaoClient client=new DefaultTaobaoClient(getTopUrl(), appkey, secret);
		VasSubscribeGetRequest req=new VasSubscribeGetRequest();
		req.setNick(nick);
		req.setArticleCode(articleCode);
		VasSubscribeGetResponse response = client.execute(req);
		return response;
	}
	
}
